package com.java.simple.smallspring.aop.framework;

import com.java.simple.smallspring.aop.AdvisedSupport;
import com.java.simple.smallspring.util.ClassUtil;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import lombok.RequiredArgsConstructor;
import org.aopalliance.intercept.MethodInterceptor;

/**
 * @author zhoujunlin
 * @date 2022年09月10日 16:29
 * @desc 基于Jdk的代理实现类
 */
@RequiredArgsConstructor
public class JdkDynamicAopProxy implements AopProxy, InvocationHandler {

    private final AdvisedSupport advisedSupport;

    @Override
    public Object getProxy() {
        return Proxy.newProxyInstance(ClassUtil.getDefaultClassLoader(),
                advisedSupport.getTargetSource().getTargetClass(), this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        // 类及方法匹配的话 执行aop增强
        if (advisedSupport.getMethodMatcher().matches(method, advisedSupport.getTargetSource().getTarget().getClass())) {
            MethodInterceptor methodInterceptor = advisedSupport.getMethodInterceptor();
            return methodInterceptor.invoke(new ReflectiveMethodInvocation(
                    advisedSupport.getTargetSource().getTarget(), method, args
            ));
        }
        // 否则执行普通的方法
        return method.invoke(advisedSupport.getTargetSource().getTarget(), args);
    }
}
